package com.demo.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;


@Slf4j
@RestController
@RequestMapping("/smart")
public class SmartController {



    @GetMapping("/{name}")
    public String test1(@PathVariable String name) {
        String uuid = IdUtil.fastSimpleUUID();

        // 获取主机名
        String hostname = "找不到";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        }catch (Exception e) {}

        // 获取主要IP地址（优先选择非回环地址）
        String ip = getLocalIpAddress();

        // 获取所有IP地址
        String allIps = getAllLocalIpAddresses();

        String lgs = "UUID="+uuid+"\n IP="+ip+"\n hostname = "+hostname+"\n 传进来的参数="+name +"所以的IP="+allIps;

        log.info("测试日志输出："+lgs);

        return lgs;
    }




    @GetMapping("/test")
    public String test1() {
        List<String> list = new ArrayList<>();
        list.add("默认值");
        return "test";
    }


    @GetMapping("/test2")
    public String test2() throws InterruptedException {
        List<String> list = new ArrayList<>();


        Thread.sleep(20000L);



        return "test";
    }



    /**
     * 获取主要IP地址（优先非回环地址）
     */
    private String getLocalIpAddress() {
        try {
            // 首先尝试获取本地主机的非回环地址
            String ip = InetAddress.getLocalHost().getHostAddress();
            if (!ip.startsWith("127.")) {
                return ip;
            }

            // 如果回环地址，则遍历所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                // 跳过回环和虚拟接口
                if (iface.isLoopback() || !iface.isUp() || iface.isVirtual()) continue;

                for (InetAddress addr : Collections.list(iface.getInetAddresses())) {
                    // 只返回IPv4地址
                    if (addr.getHostAddress().contains(":")) continue; // 跳过IPv6
                    if (!addr.isLoopbackAddress()) {
                        return addr.getHostAddress();
                    }
                }
            }
            return "127.0.0.1"; // 默认回环地址
        } catch (Exception e) {
            return "Unknown IP";
        }
    }

    /**
     * 获取所有IP地址（IPv4）
     */
    private String getAllLocalIpAddresses() {
        StringBuilder sb = new StringBuilder();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                if (iface.isLoopback() || !iface.isUp() || iface.isVirtual()) continue;

                for (InetAddress addr : Collections.list(iface.getInetAddresses())) {
                    if (addr.getHostAddress().contains(":")) continue; // 跳过IPv6
                    if (sb.length() > 0) sb.append(", ");
                    sb.append(addr.getHostAddress());
                }
            }
        } catch (Exception e) {
            return "Error retrieving IPs";
        }
        return sb.length() > 0 ? sb.toString() : "No IPs found";
    }
}
